package com.huazai.juc.cec.thread.past;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;

import static java.lang.Thread.sleep;


/**
 * 这个类有问题啊。。。不知道为什么运行不起。那就到时候视频里面再去看下吧。。。
 */
@Slf4j
public class GuardedSuspension {
    public static void main(String[] args) throws InterruptedException {
        GuardObject guardObject = new GuardObject();
        new Thread(() -> {
            try {
                sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            guardObject.complete(Arrays.asList("a", "b", "c"));
        }).start();

        Object response = guardObject.get(2500);
        if (response != null) {
            log.debug("get response: [{}] lines", ((List<String>) response).size());
        } else {
            log.debug("can't get response");
        }
    }
}

@Slf4j
class GuardObject {
    private Object response;
    private final Object lock = new Object();
    // 获取结果
    // timeout: 最大等待时间
    public Object get(long millis) throws InterruptedException {
        // 1.记录最初时间
        long begin = System.currentTimeMillis();
        // 2.已经运行的时间
        long timePassed = 0;
        while (response == null) {
            long waitTime = millis - timePassed;
            log.debug("waitTime: {}", waitTime);

            // 经历时间超过最大等待时间并且退出循环
            if (waitTime <= 0) {
                log.debug("break...");
                break;
            }
            lock.wait(waitTime);

            // 3.如果提前被唤醒，这时已经经历的时间假设为400
            timePassed = System.currentTimeMillis() - begin;

            log.debug("timePassed: {}, object is null {}", timePassed, response == null);
        }
        return response;
    }


    // 产生结果
    public void complete(Object response) {
        synchronized (lock) {
            this.response = response;
            log.debug("notify...");
            lock.notifyAll();
        }
    }
}













